﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using Spring.Context;
using YiLe.BLL.Service;

namespace YiLe.View.Users
{
    public partial class UserSaveForm : Form
    {
        private IUserService userService;
        private IRoleService roleService;
        private UserListForm parentForm;

        /// <summary>
        /// 构造方法1：传入IApplicationContext和UserListForm
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="form"></param>
        public UserSaveForm(IApplicationContext ctx, UserListForm form)
        {
            InitializeComponent();

            userService = ctx["UserService"] as IUserService;
            roleService = ctx["RoleService"] as IRoleService;
            parentForm = form;
        }

        /// <summary>
        /// 构造方法2：先执行构造方法1，再传入Use值
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="form"></param>
        /// <param name="user"></param>
        public UserSaveForm(IApplicationContext ctx, UserListForm form, Model.Domain.User user) : this(ctx, form)
        {
            tbUserID.Text = user.UserID.ToString(CultureInfo.InvariantCulture);
            tbUserName.Text = user.UserName;
            tbLoginName.Text = user.LoginName;
            tbLoginPWD.Text = user.LoginPWD;
        }

        /// <summary>
        /// 增加用户事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (ValidateForm())
            {
                Model.Domain.User user = ParseFormToUser();
                if (tbUserID.Text.Equals("0"))
                {
                    userService.Save(user);
                }
                else
                {
                    user.UserID = Int32.Parse(tbUserID.Text.Trim());
                    userService.Update(user);
                }

                parentForm.UserListForm_Load(sender, e);
                Close();
            }
        }

        /// <summary>
        /// 将Form中的输入框转换为User对象，此处需要将Role对象加入到User中
        /// </summary>
        private Model.Domain.User ParseFormToUser()
        {
            int userID = Int32.Parse(tbUserID.Text.Trim());
            string userName = tbUserName.Text.Trim();
            string userSex = "1";
            string loginName = tbLoginName.Text.Trim();
            string loginPWD = tbLoginPWD.Text.Trim();

            //填装Role的列表
            IList<Model.Domain.Role> roleList = new List<Model.Domain.Role>();
            foreach (Control c in Controls)
            {
                if (c is CheckBox)
                {
                    if ((c as CheckBox).Checked)
                    {
                        //查询数据库中的Role，将其添加到List中，然后保存到User
                        Model.Domain.Role role = roleService.Get(Int32.Parse(c.Name));
                        roleList.Add(role);
                    }
                }
            }

            Model.Domain.User u = new Model.Domain.User() { UserID = userID, UserName = userName, UserSex = userSex, LoginName = loginName, LoginPWD = loginPWD, Roles = roleList };
            return u;
        }

        /// <summary>
        /// Form验证
        /// </summary>
        /// <returns></returns>
        private bool ValidateForm()
        {
            epUserSave.Clear();
            if (tbLoginName.Text.Length == 0)
            {
                epUserSave.SetError(tbLoginName, "登录名不能为空！");
                return false;
            }
            if (tbLoginPWD.Text.Length == 0)
            {
                epUserSave.SetError(tbLoginPWD, "登录密码不能为空！");
                return false;
            }
            if (tbUserName.Text.Length == 0)
            {
                epUserSave.SetError(tbUserName, "用户姓名不能为空");
            }
            return true;
        }

        /// <summary>
        /// 读取Form的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserSaveForm_Load(object sender, EventArgs e)
        {
            IList<Model.Domain.Role> roleList = roleService.GetAll();

            int top = lbRole.Top;
            int left;
            for (int i = 0; i < roleList.Count; i++)
            {
                CheckBox cb = new CheckBox();

                Model.Domain.Role role = roleList.ElementAt(i);
                cb.Name = role.RoleID.ToString(CultureInfo.InvariantCulture);//checkbox的ID号为对应的roleID
                cb.Text = role.RoleName;//checkbox的名称对应RoleName

                if (i % 2 == 0)
                {
                    left = lbRole.Left;
                    top += cb.Height;
                }
                else
                {
                    left = lbRole.Left + i % 2 * cb.Width;
                }
                cb.Top = top;
                cb.Left = left;
                cb.Parent = this;
            }

            if (!tbUserID.Text.Trim().Equals("0"))
            {
                int userID = Int32.Parse(tbUserID.Text.Trim());
                Model.Domain.User user = userService.Get(userID);
                IList<Model.Domain.Role> userRoleList = user.Roles;

                foreach (Control c in Controls)
                {
                    if (c is CheckBox)
                    {
                        foreach (Model.Domain.Role r in userRoleList)
                        {
                            if ((c as CheckBox).Name.Equals(r.RoleID.ToString(CultureInfo.InvariantCulture)))
                            {
                                (c as CheckBox).Checked = true;
                            }
                        }
                    }
                }
            }
        }
    }
}
